package com.scraper.articles.web.controller;

import com.scraper.articles.web.model.Request;
import com.scraper.articles.web.model.SourceEnum;
import com.scraper.articles.web.service.RequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Map;

@Controller
@RequestMapping("/request")
public class RequestController {

	@Autowired
	private RequestService requestService;

	@RequestMapping(value = { "/", "/listRequests" })
	public String listRequests(Map<String, Object> map) {

		map.put("request", new Request());
		map.put("requestList", requestService.listRequests());
		map.put("sourceEnumList", SourceEnum.values());

		return "/request/listRequests";
	}

	@RequestMapping("/get/{requestId}")
	public String getRequest(@PathVariable Long requestId, Map<String, Object> map) {

		Request request = requestService.getRequest(requestId);

		map.put("request", request);

		return "/request/requestForm";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String saveRequest(@ModelAttribute("request") Request request,
			BindingResult result) {

		requestService.saveRequest(request);

		/*
		 * Note that there is no slash "/" right after "redirect:" So, it
		 * redirects to the path relative to the current path
		 */
		return "redirect:listRequests";
	}

	@RequestMapping("/delete/{requestId}")
	public String deleteRequest(@PathVariable("requestId") Long id) {

		requestService.deleteRequest(id);

		/*
		 * redirects to the path relative to the current path
		 */
		// return "redirect:../listRequests";

		/*
		 * Note that there is the slash "/" right after "redirect:" So, it
		 * redirects to the path relative to the project root path
		 */
		return "redirect:/request/listRequests";
	}
}
